package org.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.demo.entity.*;
import org.demo.mapper.*;
import org.demo.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;


@Service
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements IContractService {
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private HousesMapper housesMapper;
    @Autowired
    private AppointmentsMapper appointmentsMapper;
    @Autowired
    private IPerformanceService performanceService;
    @Autowired
    private IOrderIdService orderIdService;
    @Autowired
    private INoticeService noticeService;

    @Override
    public void add(ContractDto contractDto) {
        String id = orderIdService.getId("CONT");
        contractDto.setId(id);
        contractDto.setStatus("0");
        if (contractDto.getCreateTime()==null){
            contractDto.setCreateTime(LocalDate.now());
        }

        Houses houses = housesMapper.selectById(contractDto.getHouseId());
//        houses.setStatus("3");
//        housesMapper.updateById(houses);

        if (houses.getType().equals("1")){
            LocalDate cTime = contractDto.getCreateTime();
            int yuefen = contractDto.getYuefen();
            LocalDate eTime = cTime.plusMonths(yuefen);
            contractDto.setEndTime(eTime);

            BigDecimal cAmou = houses.getPrice().multiply(new BigDecimal(yuefen));
            contractDto.setHouseAmount(cAmou);
        }else {
            contractDto.setHouseAmount(houses.getPrice());
        }


        Contract contract = BeanUtil.copyProperties(contractDto, Contract.class);
        save(contract);

        Appointments appointments = new Appointments();
        appointments.setCustomerId(contract.getUserId());
        appointments.setHouseId(contract.getHouseId());
        appointments.setIntermediaryId(contract.getIntermediaryId());
        Appointments appointments1 = appointmentsMapper.selectChong(appointments);
        appointments1.setStatus("3");
        appointmentsMapper.updateById(appointments1);

        String content="中介已创建合同，请查看";
        noticeService.addNotice(appointments.getIntermediaryId(),appointments.getCustomerId(),appointments.getHouseId(),content,"0","0","0");


    }
    @Override
    public PageBean<ContractDto> Pagelist(Integer pageNum, Integer pageSize, Contract contract) {
        // 创建 pagebean 对象
        PageBean<ContractDto> pb = new PageBean<>();
        // 开启分页查询
        Page<ContractDto> page = PageHelper.startPage(pageNum, pageSize);
        LocalDate today = LocalDate.now();

        List<Contract> contractList = contractMapper.selectAll(contract);

        List<ContractDto> contractListDto =new ArrayList<>();
        for (int i = 0; i < contractList.size(); i++) {
            Contract cont = contractList.get(i);
            if (cont.getEndTime()!=null){
                if (cont.getEndTime().isBefore(today)) {
                    cont.setStatus("2");
                    contractMapper.updateById(cont);
                }
            }

            ContractDto contractDto = BeanUtil.copyProperties(cont, ContractDto.class);

            Users Landlord = usersMapper.selectById(contractDto.getLandlordId());
            Users getUser = usersMapper.selectById(contractDto.getUserId());

            contractDto.setUsername(getUser.getNickname());
            contractDto.setLandlordname(Landlord.getNickname());


            Houses houses = housesMapper.selectById(contractDto.getHouseId());
            contractDto.setType(houses.getType());



            contractListDto.add(contractDto);
        }




        pb.setTotal(page.getTotal());
        pb.setItems(contractListDto);
        return pb;
    }
    @Override
    public List<Contract> list(Contract contract) {
        List<Contract> contracts=lambdaQuery().eq(Contract::getId,contract.getId()).list();
        return contracts;
    }
    @Override
    public List<ContractDto> Financiallist(Contract contract) {
        List<ContractDto> contractDto = new ArrayList<>();
        if (!contract.getIntermediaryId().equals("")){
            List<ContractDto> contracts=contractMapper.AllFee(contract);
            for (int i = 0; i < contracts.size(); i++) {
                ContractDto contrac = new ContractDto();
                contrac.setYuefenAll(contracts.get(i).getYuefenAll());
                contrac.setTotalHouseFee(contracts.get(i).getTotalHouseFee());
                contrac.setTotalServiceFee(contracts.get(i).getTotalServiceFee());
                contractDto.add(contrac);
            }
        }else {
            ContractDto contracts=new ContractDto();
            contractDto.add(contracts);
        }

        return contractDto;
    }

    @Override
    public void update(Contract contract) {
        contractMapper.updateById(contract);
        Houses houses = housesMapper.selectById(contract.getHouseId());
        houses.setStatus("3");
        housesMapper.updateById(houses);

        houses.setStatus("3");
        housesMapper.updateById(houses);
        Performance performance = new Performance();
        String id = orderIdService.getId("PERF");
        performance.setId(id);
        performance.setIntermediaryId(contract.getIntermediaryId());
        performance.setContractId(contract.getId());
        performance.setAmount(contract.getHouseAmount());
        performance.setComAmount(contract.getIntAmount());
        if (contract.getCreateTime()==null){
            performance.setCreateTime(LocalDate.now());
        }else {
            performance.setCreateTime(contract.getCreateTime());
        }

        performanceService.save(performance);


        String content="恭喜支付完成 合同已生效";
        noticeService.addNotice(contract.getIntermediaryId(),contract.getUserId(),contract.getHouseId(),content,"0","0","0");
        String content2="房屋交易完成 合同已生效";
        noticeService.addNotice(contract.getIntermediaryId(),contract.getLandlordId(),contract.getHouseId(),content2,"0","0","0");


    }

    @Override
    public void delete(String id) {
        contractMapper.deleteById(id);
    }

}
